<template>
    <el-tree :data="treeData"  v-loading="loadFlag" check-on-click-node
             ref="tree"  show-checkbox
             node-key="id"  accordion highlight-current check-strictly
             @check-change="handleCheckChange">
    </el-tree>
</template>

<script>
import { buildTreeByParentId } from '@/utils/treeUtil'

export default {
  components: {},
  props: {
  },
  data () {
    return {
      currentRow: null,
      tableData: null,
      treeData: null,
      loadFlag: true
    }
  },
  mounted () {
  },
  methods: {
    // 单选会清除选项
    clearAll () {
      this.$refs.tree.setCheckedKeys([])
    },
    setData (tableData, options) {
      this.tableData = tableData
      this.treeData = buildTreeByParentId(tableData, options)
      this.loadFlag = false
    },
    handleCheckChange (data, checked) {
      if (checked) {
        this.$refs.tree.setCheckedKeys([data.id])
      }
      console.log('handleNodeClick ', data)
      this.$emit('nodeChange')
    },
    getRoot () {
      return this.treeData[0]
    },
    getNodePath () {
      const nodes = this.$refs.tree.getCheckedNodes()
      const nodePath = []
      if (nodes.length == 1) {
        const nodeItem = nodes[0]
        let currentNode = this.$refs.tree.getNode(nodeItem.id)
        nodePath.push(this.transformNode(currentNode))
        while (currentNode.parent != null) {
          currentNode = currentNode.parent
          if (currentNode.parent == null) {
            break
          }
          nodePath.push(this.transformNode(currentNode))
        }
      }
      return nodePath.reverse()
    },
    getNoLeafNodePath () {
      const nodePath = this.getNodePath()
      return nodePath.filter((item) => !item.isLeaf)
    },
    transformNode (treeNode) {
      return { id: treeNode.data.id, label: treeNode.data.label, isLeaf: treeNode.isLeaf }
    },
    removeNodeById (delId) {
      this.$refs.tree.remove({ id: delId })
    },
    append (data, parantId) {
      const parentNode = this.$refs.tree.getNode(parantId)
      this.$refs.tree.append(data, parentNode)
    },
    updateOrInsert (data, parentId) {
      const node = this.$refs.tree.getNode(data.id)
      if (node == null) {
        this.append(data, parentId)
      } else {
        node.data.label = data.label
      }
    }
  }
}
</script>
